
//为节点添加validType
function addValidateOldName(oldNameNode, validateName) {
    var oldRoleName = oldNameNode.val();
    oldNameNode.attr("validType", validateName + "('" + oldRoleName + "')");
}

//自定义验证规则
$.extend($.fn.validatebox.defaults.rules, {
    noEmptyNumber:{
        validator:function(value, param){
            if(value && isMoreThan0Number(value) && value>0){
                return true;
            }else{
                return false;
            }
        },
        message: '请输入非空正数.'
    },
    unique: {
        validator: function (value, param) {
            if (value != param) {
                var flag = false;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: getContextPath() + "/roleController/selectRoleName.html",
                    data: {roleName: value},
                    before: function () {
                        parent.$.messager.progress({
                            title: '提示',
                            text: '数据处理中，请稍后....'
                        });
                    },
                    success: function (data) {
                        parent.$.messager.progress('close');
                        if (data && isSuccess(data.result)) {
                            if (data.result == "10050") {
                                flag = true;
                            } else if (data.result == "10040") {
                                flag = false;
                            }
                        } else {
                            commonError(data.result, data.message);
                        }
                    },
                    timeout: 1000,
                    error: function (result) {
//			internalError();
                        parent.$.messager.progress('close');
                        templateInternalError(result.responseText);


                    }
                });
                return flag;
            } else {
                return true;
            }
        },
        message: '角色名称已存在.'
    },
    uniqueUserNo: {
        validator: function (value, param) {
            if (value != param) {
                var flag = false;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: getContextPath() + "/sysUserController/selectUserNoAndUserName.html",
                    data: {userNo: value},
                    before: function () {
                        parent.$.messager.progress({
                            title: '提示',
                            text: '数据处理中，请稍后....'
                        });
                    },
                    success: function (data) {
                        parent.$.messager.progress('close');
                        if (data && isSuccess(data.result)) {
                            if (data.result == "10050") {
                                flag = true;
                            } else if (data.result == "10040") {
                                flag = false;
                            }
                        } else {
                            commonError(data.result, data.message);
                        }
                    },
                    timeout: 1000,
                    error: function (result) {
//			internalError();
                        parent.$.messager.progress('close');
                        templateInternalError(result.responseText);

                    }
                });
                return flag;
            } else {
                return true;
            }

        },
        message: '用户代码已存在.'
    },
    uniqueUserName: {
        validator: function (value, param) {
            if (value != param) {
                var flag = false;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: getContextPath() + "/sysUserController/selectUserNoAndUserName.html",
                    data: {userName: value},
                    before: function () {
                        parent.$.messager.progress({
                            title: '提示',
                            text: '数据处理中，请稍后....'
                        });
                    },
                    success: function (data) {
                        parent.$.messager.progress('close');
                        if (data && isSuccess(data.result)) {
                            if (data.result == "10050") {
                                flag = true;
                            } else if (data.result == "10040") {
                                flag = false;
                            }
                        } else {
                            commonError(data.result, data.message);
                        }
                    },
                    timeout: 1000,
                    error: function (result) {
//			internalError();
                        parent.$.messager.progress('close');
                        templateInternalError(result.responseText);

                    }
                });
                return flag;
            } else {
                return true;
            }
        },
        message: '账号已存在.'
    },
    companyNoEmpty:{
        validator: function (value, param){
           return !param;
        },
        message: '请先填写部门代码.'
    },
    uniqueDeptName: {
        validator: function (value, param) {
            if (value != param) {
                var flag = false;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: getContextPath() + "/deptController/selectIsDeptName.html",
                    data: {deptName: value,
                        companyNo: $('#companyNo').val()},
                    before: function () {
                        parent.$.messager.progress({
                            title: '提示',
                            text: '数据处理中，请稍后....'
                        });
                    },
                    success: function (data) {
                        parent.$.messager.progress('close');
                        if (data && isSuccess(data.result)) {
                            if (data.result == "10050") {
                                flag = true;
                            } else if (data.result == "10040") {
                                flag = false;
                            }
                        } else {
                            commonError(data.result, data.message);
                        }
                    },
                    timeout: 1000,
                    error: function (result) {
//			internalError();
                        parent.$.messager.progress('close');
                        templateInternalError(result.responseText);

                    }
                });
                return flag;
            } else {
                return true;
            }
        },
        message: '部门名称已存在.'
    },
    biggerAppBalance: {
        validator: function (value, param) {
            return !(parseFloat(value)>parseFloat($(param[0]).text()));
        },
        message: '申请付款金额大于合同剩余未付款金额.'
    }
});

//获取combobox文本内容
//id
//orName 属性名
//TODO重写
function getComboboxText(data, id){
    for (var i = 0; i < data.length; i++) {
        if (data[i].id == id) {
            return data[i].orName;
        }
    }
}

//获取tree文字
//id
//Text
var treeNodeName;
function getComboTreeText(data,id){
    for (var i = 0; i < data.length; i++) {
        var children = data[i].children;
        if(children&&children.length>0){
                getComboTreeText(children,id);
        }else{
            if(data[i].id == id){
                treeNodeName = data[i].text
                return treeNodeName;
            }
        }
    }
    return treeNodeName;
}

//form数据拼接
(function ($) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };
})(jQuery);

//日期控件 日期格式化（设置默认日期使用）
function myformatter(date){
    var y = date.getFullYear();
    var m = date.getMonth()+1;
    var d = date.getDate();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
}

//生成uuid
var random4 = function() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
var UUID = function() {
    return (random4() + random4() + "-" + random4() + "-" + random4() + "-" + random4() + "-" + random4() + random4() + random4());
};

//拓展单元格编辑方法
$.extend($.fn.datagrid.methods, {
    editCell: function(jq,param){
        return jq.each(function(){
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field){
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

//验证是不是为空
function isEmpty(val){
    return !val;
}

//验证是不是数字
function isMoreThan0Number(val){
     var reg = /^\d+(?=\.{0,1}\d+$|$)/
    return reg.test(val);
}

//显示验证不通过的提示信息
function showValidteMessage(value) {
    if (value && value != "true") {
        parent.$.messager.alert('提示', "验证不通过 " + value, 'info');
        return false;
    }
    return true;
}

//状态方法
//flag 有值的时候刷新无分页的view页面
function changeStatus(url, id, status, funStr) {
    var postData = {'id': id, 'status': status};
    postAjax(url, JSON.stringify(postData), funStr, {async:false});

}

function searchFun(url,node,funcName ) {
    var postData = $.serializeObject($('#searchForm'));
    initAjaxDataGrid(url, node, funcName({postData: postData}));
}

//TODO bug
//kk.toFixed(2)
//"1.490999999999999"
//Number.prototype.toFixed = function(fractionDigits)
//{
//    return (Math.round(this * Math.pow(10, fractionDigits)) / Math.pow(10, fractionDigits) + Math.pow(10, -(fractionDigits + 1))).toString().slice(0, -1);
//}

function accAdd(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2))
    return (arg1*m+arg2*m)/m
}
//给Number类型增加一个add方法，调用起来更加方便。
Number.prototype.add = function (arg){
    return accAdd(arg,this);
}

Number.prototype.toFixed=function(len)
{
    var tempNum = 0;
    var s;
    var s1 = this + "";
    var start = s1.indexOf(".");

    //截取小数点后,0之后的数字，判断是否大于5，如果大于5这入为1

    if(s1.substr(start+len+1,1)>=5)
        tempNum=1;

    //计算10的len次方,把原数字扩大它要保留的小数位数的倍数
    var temp = Math.pow(10,len);
    //求最接近this * temp的最小数字
    //floor() 方法执行的是向下取整计算，它返回的是小于或等于函数参数，并且与之最接近的整数
    s = Math.floor(Math.round(this * temp));
    return s/temp;
}

function formatNum(str){
    str = str?str:0;
    if(str!=undefined){
        str = str.toString();
        var newStr = "";
        var count = 0;

        if(str.indexOf(".")==-1){
            for(var i=str.length-1;i>=0;i--){
                if(count % 3 == 0 && count != 0){
                    newStr = str.charAt(i) + "," + newStr;
                }else{
                    newStr = str.charAt(i) + newStr;
                }
                count++;
            }
            str = newStr + ".00"; //自动补小数点后两位
            return str;
        }
        else
        {
            for(var i = str.indexOf(".")-1;i>=0;i--){
                if(count % 3 == 0 && count != 0){
                    newStr = str.charAt(i) + "," + newStr;
                }else{
                    newStr = str.charAt(i) + newStr; //逐个字符相接起来
                }
                count++;
            }
            str = newStr + (str + "00").substr((str + "00").indexOf("."),3);
            return str;
        }
    }
}

function formatWeight(str){
    str = str?str:0;
    if(str!=undefined){
        str = str.toString();
        var newStr = "";
        var count = 0;

        if(str.indexOf(".")==-1){
            for(var i=str.length-1;i>=0;i--){
                if(count % 3 == 0 && count != 0){
                    newStr = str.charAt(i) + "," + newStr;
                }else{
                    newStr = str.charAt(i) + newStr;
                }
                count++;
            }
            //str = newStr + ".00"; //自动补小数点后两位
            return str;
        }
        else
        {
            for(var i = str.indexOf(".")-1;i>=0;i--){
                if(count % 3 == 0 && count != 0){
                    newStr = str.charAt(i) + "," + newStr;
                }else{
                    newStr = str.charAt(i) + newStr; //逐个字符相接起来
                }
                count++;
            }
            return str;
        }
    }
}

//通过状态名称获取状态id
function changeStatusVal(str, statusObj) {
    for(var i in statusObj){
        if (statusObj[i] === str) {
            return i;
        }
    }
}

//税额计算方法
function calculateTax(total, taxRate) {
    return (total*(taxRate)/(1+parseFloat(taxRate)));
}

//设置按钮disable状态
//nodeArray和statusArray长度相同
//statusArray 为0,1 0为disable,1为enable
function setLinkButtonStatus(nodeArray,statusArray){
    $.each(nodeArray, function(index, value){
        nodeArray[index].linkbutton(statusArray[index]?'enable':'disable');
    });
}

function getColumnIndex(columns, name){
    for(var i=0;i<columns.length;i++){
        if(columns[i].field == name){
            return i;
        }
    }
}

//TODO modeify $field = $('td',$panel);
var editIndex = undefined;
function endEditing(node) {
    if (editIndex === undefined) {
        return true
    }
    var $panel = node.datagrid("getPanel");
    var $field = $('td', $panel);
    var $input = $("input", $field);
    $input.removeClass("validatebox-text validatebox-invalid").unbind('focus').unbind('blur');
    if (node.datagrid('validateRow', editIndex)) {
        node.datagrid('endEdit', editIndex);
        //if(node.datagrid('getData').rows[editIndex].statusSub ===undefined){
        //    node.datagrid('getData').rows[editIndex].statusSub = rowData.statusSub;
        //}
        editIndex = undefined;
        return true;
    } else {
        node.datagrid('highlightRow', editIndex);
        return false;
    }
}


function errorFunction(resultData){
    parent.$.messager.alert('提示', resultData.result + " " + resultData.message, 'info');
}

// ajax post
//参数 url 链接 ， postData post使用的数据， successFunction 成功时的回调函数函数
//options errorFunction 返回错误时的回调函数
//        passArguments 成功时回调函数参数
//        errorArguments 失败时回调函数参数
//        successMessage 成功时的提示信息
var postAjax = function (url, postData, successFunction, options) {
    //默认错误返回函数 错误函数参数 正确函数参数
    var defaultOptions = {
        errorFunction: errorFunction,
        successArguments: "",
        errorArguments: "",
        successMessage: "",
        type:"post",
        async:false
    }
    var currentOptions = $.extend(defaultOptions, options);
    $.ajax({
        type: currentOptions.type,
        data: postData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: getContextPath() + url,
        before: function () {
            parent.$.messager.progress({
                title: '提示',
                text: '数据处理中，请稍后....'
            });
        },
        success: function (resultData) {
            parent.$.messager.progress('close');
            if (resultData && isSuccess(resultData.result)) {
                    if (currentOptions && currentOptions.successArguments) {
                        successFunction(resultData, currentOptions.successArguments);
                    } else {
                        successFunction(resultData);
                    }
            } else {
                //if (currentOptions && currentOptions.errorFunction) {
                parent.$.messager.progress('close');
                defaultOptions.errorFunction(resultData);
                //} else {
                //    if (currentOptions && currentOptions.errorArguments) {
                //        errorFunction(resultData, currentOptions.errorArguments.split(','));
                //    } else {
                //
                //    }
                //}
            }
        },
        error: function (result) {
            parent.$.messager.progress('close');
//			internalError();
            templateInternalError(result.responseText);
        }
    });
}

$.extend($.fn.datagrid.defaults.editors, {
    combogrid: {
        init: function(container, options){
            var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
            input.combogrid(options);
            return input;
        },
        destroy: function(target){
            $(target).combogrid('destroy');
        },
        getValue: function(target){
            return $(target).combogrid('getValue');
        },
        setValue: function(target, value){
            $(target).combogrid('setValue', value);
        },
        resize: function(target, width){
            $(target).combogrid('resize',width);
        }
    }
});

//总数据 combo保存的数据 combo保存数据key 返回数据的key
function getComboboxTextC(data,value,nodeName1,nodeName2){
    for (var i = 0; i < data.length; i++) {
        if (data[i][nodeName1] == value) {
            return data[i][nodeName2];
        }
    }
}

function isRepeat(packageArrray) {
    var hash = {};
    for(var i in packageArrray) {
        if(hash[packageArrray[i]])
        {
            return i;
        }
        // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
        hash[packageArrray[i]] = true;
    }
    return -1;
}
